import { Component, OnInit } from '@angular/core';
import {LoadingService} from '../../../shared/loading.service';
import {SystemService} from '../system.service';
import {AlertService} from '../../../shared/alert.service';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-system-roles',
  templateUrl: './system-roles.component.html',
  styleUrls: ['./system-roles.component.scss']
})
export class SystemRolesComponent implements OnInit {
// 角色管理数据
  public rolesDataArr: Array<any> = [];
  public roleFunction: Array<any>= [];
  public roleName: string;

  //  模态窗口
  public delectModal: Boolean = false; // 绿色框
  public dangerModal: Boolean = false; // 红色框
  public completePrompt: String; // 红色框提示信息
  public issuccess: Boolean = false; // 框的颜色显示
  public modelBody: string; // 绿色框的提示信息
  public operateModal: Boolean = false; // 操作设置模态框

  public delectindexId: number; // 要进行操作的对象ID
    public noDatastring: Boolean = true; // 暂无数据显示

  // 保存所有权限的数组
  public allPerData: Array<any> = [];
  // 获取的每个ID的类型 的数组
    public typeArr: Array<any> = [];
  // 要操作的 id
    public operateId: string;
    // 删除的 id
    public delId: string;
    // 列表中角色的数量
    public rolesCount: any;

  constructor(
      public loading: LoadingService,
      public service: SystemService,
      public alert: AlertService,
      public routes: ActivatedRoute

  ) { }

  ngOnInit() {
   this.getRolesData();
   this.getOperationLists();
   this.routes.params.subscribe(
       params => {
              this.delId = params['id'];
       }
   );
  }
//  获取角色管理列表
  getRolesData() {
      this.loading.show();
      const params = {
          token: localStorage.token,
      };
      this.service.getRoles(params).subscribe(res => {
          if (res['data']['length'] === 0) {
              this.noDatastring = true;
          }else {
              this.noDatastring = false;
              this.rolesDataArr = res['data'];
              this.rolesCount = res['data'].length;
              // this.totalItems = res['data']['total'];
          }
          setTimeout(() => {
            this.loading.hide();
          })
      }, error => {
          this.alert.show('网络错误');
          // window.location.reload();
      });
  };
//  获取操作设置列表所有的权限
  getOperationLists() {
    this.loading.show();
    const params: any = {
      token: localStorage.token
    };
    this.service.getOperationRoles(params).subscribe(res => {
      this.loading.hide();
      this.allPerData = res['data'];
      this.allPerData.map((val, ind) => {
          val['checked'] = false; // 首先所有的选择都是 false
        })
    }, error => {
        this.alert.show('网络错误');
        // window.location.reload();
    });
  }
  // 点击操作设置
    operation(id) {
      this.allPerData.map((val, ind) => {
         val['checked'] = false;
      });
      this.operateId = id;
      this.operateModal = true;
      this.issuccess = true;
      this.getPerDetail(this.operateId);
    }
    getPerDetail(id) {
      const params = {
          token: localStorage.token,
          id: this.operateId
      };
      this.service.operationRoles(params).subscribe(res => {
          this.allPerData.map((value, index) => {
             res['data']['0']['permission'].map((u, j) => {
               if (value['id'] === u) {// 表示被选中状态
                 value['checked'] = true;
               }
             })
          })
      }, error => {
          this.alert.show('网络错误');
          // window.location.reload();
      });
    }
    // 确定 设置按钮
    sureSet() {
      const params = {
          token: localStorage.token,
          rid: this.operateId,
          pid: JSON.stringify(this.typeArr).replace(/\[|\]/g, '')
      };
      this.service.setOperationRoles(params).subscribe(res => {
          if (res['code'] === 0) {
              this.alert.show('设置成功');
              this.operateModal = false;
          }else {
              this.alert.show('设置失败');
              this.operateModal = false;
          }
      }, error => {
          this.alert.show('网络错误');
          // window.location.reload();
      });
    }
    changeType(event: Boolean , i) {
      // 如果角色没有被选中则加入数组，如果已经被选中则从数组中取消
        if (event) {
           this.typeArr.push(i);
        }else {
           this.typeArr.map((v, j) => {
               if (v === i) {
                  this.typeArr.splice(j, 1);
               }
           })
        }
    }
    // 取消设置按钮
    return() {
      this.operateModal = false;
      this.getOperationLists();
    }

//  角色添加
    addmodify() {
      this.loading.show();
      if (this.roleName === undefined || this.roleName === '') {
        this.delectModal = true;
        setTimeout(() => {
          this.loading.hide();
        }, 300);
        this.issuccess = false;
        this.modelBody = '名称不能为空';
      }else {
        const params = {
          token: localStorage.token,
          name: this.roleName
        };
        this.service.addRoles(params).subscribe(res => {
          setTimeout(() => {
            this.loading.hide();
            }, 200);
          if (this.rolesCount < 10) {
              if (res['code'] === 0) {
                  this.delectModal = true;
                  this.issuccess = true;
                  this.modelBody = '管理角色添加成功';
                  this.getRolesData();
              }else {
                  this.delectModal = true;
                  this.issuccess = false;
                  this.modelBody = res['msg']
              }
          }else {
              this.delectModal = true;
              setTimeout(() => {
                  this.loading.hide();
              }, 200);
              this.issuccess = false;
              this.modelBody = '只能添加10个角色';
          }
        },  error => {
          this.loading.hide();
          this.alert.show('网络错误');
        });
      }
    };

    // 点击删除按钮
    delectIndex(id: number) {
      this.delectindexId = id;
      this.dangerModal = true;
      this.completePrompt = '你确定要删除吗？';
    }

//  红色取消 "x"
    hideModal() {
      this.dangerModal = false; // 红色框消失
      setTimeout(() => {
        this.loading.hide();
      }, 300);
    }

  // 是否确定删除(红框变绿框)
    confirmDelete() {
      this.loading.show();
      const params: any = {
        token: localStorage.token,
        id: this.delectindexId
      };
      this.service.rolesDelete(params).subscribe(res => {
        this.dangerModal = false;
        this.loading.hide();
        if (res['code'] === 0) {
          this.delectModal = true; // 绿框出现
          this.issuccess = true; // 框的颜色为绿色
          this.modelBody = '删除成功！'; // 提示信息
            this.getRolesData();
        }else {
          this.delectModal = true;
          this.issuccess = false; // 框的颜色变为红色
          this.modelBody = res['msg']; // 提示信息
        }
      });
    }
    // 绿色删除 取消/确认
    confirmshutdown() {
      this.loading.show();
      this.delectModal = false; // 绿色的框消失
      this.roleName = '';
      if (this.issuccess = true) {
        const params = {
          token: localStorage.token
        };
        this.service.getRoles(params).subscribe(res => {
          this.rolesDataArr = res['data']['data'];
          this.loading.hide();
          this.getRolesData();
        }, error => {
          this.loading.hide();
          this.alert.show('网络出错');
        });
      }
      setTimeout(() => {
        this.loading.hide();
        }, 300);
    }
}
